<?php
/**
 * 联盟数据表
 */
namespace app\common\model;

use think\Model;
use think\Db;
use think\model\concern\SoftDelete;
use app\common\model\UserModel;
use app\common\model\UserGradeModel;

class UflModel extends Model
{
    use SoftDelete;
    protected $name = 'user_fund_log';

    /**
     * 插入订单表
     *
     * @param  [type] $array
     * deal_type 交易类型   deal_amount 交易金额    uid 用户id
     * tid 桌子id     innings 局数 // 5个值
     * @return [type]        [description]
     */
    public function insertOrder($array)
    {
        $insert = $array;
        $insert['order_no'] = 'BT'.date('YmdHis').mt_rand(10,99).$array['uid'];
        $insert['deal_before'] = 0;
        $insert['deal_after'] = 0;
        $insert['status'] = 1;
        $insert['remake'] = '结算订单';

        $this->balanceChange($array);
        $this->insertGrade($array);
        return $this->save($insert);
    }

    /**
     * 直接更新余额
     *
     * @return [type]         [description]
     */
    protected function balanceChange($array)
    {
        $uModel = new UserModel();
        $amount = $array['deal_amount'];

        if ($array['deal_type'] == ORDER_TYPE_BETLOSE) {
            $amount = 0 - $amount;
        }

        if ($array['deal_type'] == ORDER_TYPE_BETBACE ||
            $array['deal_type'] == ORDER_TYPE_BETWIN) {
            return $uModel->incBalance($array['uid'], $amount);
        }

        return false;
    }

    /**
     * 插入战绩表
     *
     * @return [type]         [description]
     */
    protected function insertGrade($array)
    {
        $ugModel = new UserGradeModel();
        $win = $array['deal_amount'];

        if ($array['deal_type'] == ORDER_TYPE_BETLOSE) {
            $win = 0 - $win;
        }
        if ($array['deal_type'] == ORDER_TYPE_BETBACE) {
            $win = 0 - ($array['bet_amount'] - $win);
        }

        $save = [
            'uid' => $array['uid'],
            'win' => $win,
            'tid' => $array['tid'],
            'innings' => $array['innings']
        ];
        return $ugModel->save($save);
    }
}
